"""
场地相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.schemas.venue import (
    VenueResponse, VenueCreate, VenueUpdate, VenueFilter,
    TimeSlotResponse, TimeSlotCreate, Location
)
from app.schemas.common import ApiResponse, PageData
from app.models.venue import Venue, TimeSlot
from app.models.user import User
from app.utils.helpers import generate_id, calculate_distance

router = APIRouter()


@router.get("/search", response_model=ApiResponse[PageData[VenueResponse]])
async def search_venues(
    keyword: str = Query(..., description="搜索关键词"),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """
    搜索场地
    支持按名称、地址模糊搜索
    """
    query = db.query(Venue).filter(
        (Venue.name.like(f"%{keyword}%")) |
        (Venue.address.like(f"%{keyword}%"))
    )
    
    # 分页
    total = query.count()
    venues = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    # 转换为响应格式
    venue_list = []
    for venue in venues:
        venue_dict = venue.to_dict()
        venue_list.append(VenueResponse(**venue_dict))
    
    return ApiResponse(
        data=PageData(
            list=venue_list,
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.get("/list", response_model=ApiResponse[PageData[VenueResponse]])
async def get_venue_list(
    city: Optional[str] = Query(None),
    type: Optional[str] = Query(None),
    minPrice: Optional[float] = Query(None),
    maxPrice: Optional[float] = Query(None),
    grassType: Optional[str] = Query(None),
    sortBy: str = Query("distance"),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """
    获取场地列表
    支持筛选和排序
    """
    query = db.query(Venue)
    
    # 筛选条件
    if city:
        query = query.filter(Venue.city_id == city)
    if type:
        query = query.filter(Venue.type == type)
    if minPrice is not None:
        query = query.filter(Venue.price >= minPrice)
    if maxPrice is not None:
        query = query.filter(Venue.price <= maxPrice)
    if grassType:
        query = query.filter(Venue.grass_type == grassType)
    
    # 排序
    if sortBy == "price":
        query = query.order_by(Venue.price.asc())
    elif sortBy == "rating":
        query = query.order_by(Venue.rating.desc())
    
    # 分页
    total = query.count()
    venues = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    # 转换为响应格式
    venue_list = []
    for venue in venues:
        venue_dict = venue.to_dict()
        venue_list.append(VenueResponse(**venue_dict))
    
    return ApiResponse(
        data=PageData(
            list=venue_list,
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.get("/detail/{venue_id}", response_model=ApiResponse[VenueResponse])
async def get_venue_detail(
    venue_id: str,
    db: Session = Depends(get_db)
):
    """获取场地详情"""
    venue = db.query(Venue).filter(Venue.id == venue_id).first()
    if not venue:
        raise HTTPException(status_code=404, detail="场地不存在")
    
    venue_dict = venue.to_dict()
    return ApiResponse(data=VenueResponse(**venue_dict))


@router.get("/time-slots", response_model=ApiResponse[List[TimeSlotResponse]])
async def get_venue_time_slots(
    venueId: str = Query(...),
    date: str = Query(...),
    db: Session = Depends(get_db)
):
    """获取场地时段"""
    time_slots = db.query(TimeSlot).filter(
        TimeSlot.venue_id == venueId,
        TimeSlot.date == date
    ).all()
    
    return ApiResponse(
        data=[TimeSlotResponse(**slot.to_dict()) for slot in time_slots]
    )


@router.post("/favorite", response_model=ApiResponse[str])
async def favorite_venue(
    venueId: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """收藏场地"""
    if not current_user.favorite_venues:
        current_user.favorite_venues = []
    
    if venueId not in current_user.favorite_venues:
        current_user.favorite_venues.append(venueId)
        db.commit()
    
    return ApiResponse(data="收藏成功")


@router.post("/unfavorite", response_model=ApiResponse[str])
async def unfavorite_venue(
    venueId: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """取消收藏"""
    if current_user.favorite_venues and venueId in current_user.favorite_venues:
        current_user.favorite_venues.remove(venueId)
        db.commit()
    
    return ApiResponse(data="取消收藏成功")

